package archer.framework.groovy.engine;

import archer.framework.core.exception.BaseException;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import groovy.lang.Script;
import jodd.io.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;

/**
 * @author christ
 * @date 2016/6/2
 */
public class GroovyEngine {

    private static Logger logger = LoggerFactory.getLogger(GroovyEngine.class);

    private static GroovyShell shell = new GroovyShell();

    /**
     * 执行脚本
     *
     * @param file
     * @param params
     * @return
     */
    public static Object runScript(String file, Map params) {

        Script script;
        try {
            script = shell.parse(FileUtil.readString(file));
        } catch (IOException e) {
            logger.error("GroovyEngine>>读取文件" + file + "出错", e);
            throw new BaseException(e);
        }

        script.setBinding(new Binding(params));
        return script.run();
    }

    /**
     * 执行脚本
     *
     * @param file
     * @return
     */
    public static Object runScript(String file) {

        return runScript(file, null);
    }

    /**
     * 执行脚本，但不抛出异常
     *
     * @param file
     * @param params
     * @return
     */
    public static Object runScriptSilently(String file, Map params) {

        try {
            return runScript(file, params);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 执行脚本，但不抛出异常
     *
     * @param file
     * @return
     */
    public static Object runScriptSilently(String file) {

        return runScriptSilently(file, null);
    }

    /**
     * 执行方法
     *
     * @param file
     * @param method
     * @param args
     * @return
     */
    public static Object invokeMethod(String file, String method, Object args) {

        Script script;
        try {
            script = shell.parse(FileUtil.readString(file));
        } catch (IOException e) {
            logger.error("GroovyEngine>>读取文件" + file + "出错", e);
            throw new BaseException(e);
        }

        return script.invokeMethod(method, args);
    }

    /**
     * 执行方法
     *
     * @param file
     * @param method
     * @return
     */
    public static Object invokeMethod(String file, String method) {

        return invokeMethod(file, method, null);
    }

    /**
     * 执行方法，但不抛出异常
     *
     * @param file
     * @param method
     * @param args
     * @return
     */
    public static Object invokeMethodSilently(String file, String method, Object args) {

        try {
            return invokeMethod(file, method, args);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 执行方法，但不抛出异常
     *
     * @param file
     * @param method
     * @return
     */
    public static Object invokeMethodSilently(String file, String method) {

        return invokeMethodSilently(file, method, null);
    }

}
